﻿using CommonUtils;
using ControllerGenerator.Commands;
using Microsoft;
using Microsoft.VisualStudio.Shell;
using System;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using Task = System.Threading.Tasks.Task;

namespace ControllerGenerator
{
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [Guid("e15fb2dd-d91c-465e-9f74-f9343cd43da2")]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    public sealed class ControllerGenerator : AsyncPackage
    {
        static readonly Guid _menuGroupId = new Guid("f0a65cda-66ff-4da1-a8c5-a10f3c89245f");
        static OleMenuCommandService _commandService;

        private static void AddMenuCommand(int id, EventHandler handler)
        => _commandService.AddCommand(new MenuCommand(handler, new CommandID(_menuGroupId, id)));

        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken);

            _commandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Assumes.Present(_commandService);

            EditorUtil.SetServiceProvider(this);

            ///显示顺序是按照ID来的，跟添加顺序和ASCII顺序无关，ID随便写，但是要与vsct中统一
            AddMenuCommand(9000, DbContextGenerator.Handler);
            AddMenuCommand(9001, DbControllerGenerator.Handler);
            AddMenuCommand(9002, FileControllerGenerator.Handler);
            "欢迎使用Controller生成插件.".Print();
        }
    }
}
